package de.hska.util;

import static de.hska.util.WebConstants.RESOURCE_BUNDLE;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

import javax.faces.application.FacesMessage;
import javax.faces.application.FacesMessage.Severity;
import javax.faces.context.FacesContext;

public class WebMessagesUtil {
	private static Map<String, ResourceBundle> resourceBundles;
	
	static {
		resourceBundles = new HashMap<String, ResourceBundle>();
		
		ResourceBundle bundle = ResourceBundle.getBundle(RESOURCE_BUNDLE, Locale.ENGLISH);
		resourceBundles.put(Locale.ENGLISH.getLanguage(), bundle);
		
		bundle = ResourceBundle.getBundle(RESOURCE_BUNDLE, Locale.GERMAN);
		resourceBundles.put(Locale.GERMAN.getLanguage(), bundle);
	}
	
	
	/**
	 * F&uuml;r das Exception-Handling bei Managed Beans
	 */
	public static FacesMessage saveFacesMessage(Severity severity, String msgKey, String clientId, Object... args) {
		final FacesContext ctx = FacesContext.getCurrentInstance();
		final FacesMessage facesMsg = getFacesMessage(severity, ctx, msgKey, args);
		ctx.addMessage(clientId, facesMsg);
		
		return facesMsg;
	}

	public static FacesMessage getFacesMessage(Severity severity, FacesContext ctx, String msgKey, Object... args) {
		String msg = getMessage(ctx, msgKey, args);
		final FacesMessage facesMsg = new FacesMessage(severity, msg, null);
		return facesMsg;
	}

	public static String getMessage(FacesContext ctx, String msgKey, Object... args) {
		final String msgPattern = getMessagePattern(ctx, msgKey);
		
		final MessageFormat formatter = new MessageFormat(msgPattern);
		String msg = formatter.format(args);
		return msg;
	}
	
	private static String getMessagePattern(FacesContext ctx, String msgKey) {
		final Locale locale = ctx.getViewRoot().getLocale();
		ResourceBundle bundle = resourceBundles.get(locale.getLanguage());
		if (bundle == null) {
			// Falls nachtraeglich eine neue Sprache in faces-config.xml eingetragen wird
			bundle = ResourceBundle.getBundle(RESOURCE_BUNDLE, locale);
			resourceBundles.put(locale.getLanguage(), bundle);
		}
		
		final String msgPattern = bundle.getString(msgKey);
		return msgPattern;
	}
}

